package com.example.app;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app.Websocket.APP;
import com.example.app.Websocket.WebRTCManager;
import com.permissionx.guolindev.PermissionX;
import org.webrtc.SurfaceViewRenderer;
public class VideoChatActivity extends AppCompatActivity implements WebRTCManager.WebRTCListener { // 实现WebRTC监听接口
    private WebRTCManager webRTCManager;
    private SurfaceViewRenderer localVideoView;
    private SurfaceViewRenderer remoteVideoView;
//    private EditText etToUser;
    private Button btnCall;
    private Button btnHangup;
    private String targetUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videochatpage);
        localVideoView = findViewById(R.id.local_video);
        remoteVideoView = findViewById(R.id.remote_video);
        targetUser = getIntent().getStringExtra("TARGET_USER_ID");
        checkPermissions();
        initViews();
        String incomingCallUser = getIntent().getStringExtra("CALL_FROM_USER");
        if (incomingCallUser != null) {
            showIncomingCallDialog(incomingCallUser);
        }
    }
    private void initViews() {
        localVideoView = findViewById(R.id.local_video);
        remoteVideoView = findViewById(R.id.remote_video);
//        etToUser = findViewById(R.id.et_to_user);
        btnCall = findViewById(R.id.btn_call);
        btnHangup = findViewById(R.id.btn_hangup);
        btnCall.setOnClickListener(v -> startCall());
        btnHangup.setOnClickListener(v -> hangup());
        Button btnSwitchCamera = findViewById(R.id.btn_switch_camera);
        btnSwitchCamera.setOnClickListener(v -> switchCamera());
    }
    private void checkPermissions() {
        PermissionX.init(this).permissions(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO).request((allGranted, grantedList, deniedList) -> {
            if (allGranted) initWebRTC();
            else finish();
        });
    }
    private void initWebRTC() {
        webRTCManager = APP.getWebRTCManager();
        webRTCManager.setListener(this);
        webRTCManager.initializeVideo(localVideoView, remoteVideoView);
        if (targetUser != null && getIntent().getStringExtra("CALL_FROM_USER") == null) {
            webRTCManager.startCall(targetUser);
        }
    }
    private void showIncomingCallDialog(String fromUser) {
        new AlertDialog.Builder(this).setTitle("来电").setMessage(fromUser + "的视频请求").setPositiveButton("接听", (d, w) -> webRTCManager.acceptCall(fromUser)).setNegativeButton("拒绝", (d, w) -> webRTCManager.rejectCall(fromUser)).show();
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (webRTCManager != null) webRTCManager.setListener(this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (webRTCManager != null) webRTCManager.setListener(null);
    }
    private void startCall() {
//        String targetUser = etToUser.getText().toString();
        if (!targetUser.isEmpty()) {
            webRTCManager.startCall(targetUser);
        }
    }
    private void hangup() {
        webRTCManager.hangup();
        startActivity(new Intent(VideoChatActivity.this, ChatpageActivity.class));
        finish();

    }
    private void switchCamera() {
        webRTCManager.switchCamera();
    }
    @Override
    public void onRemoteStreamAdded() {
        runOnUiThread(() ->
                Toast.makeText(this, "已连接远程视频", Toast.LENGTH_SHORT).show());
    }
    @Override
    public void onCallReceived(String fromUser) {
        runOnUiThread(() ->
                new android.app.AlertDialog.Builder(this).setTitle("来电").setMessage(fromUser + "请求视频通话").setPositiveButton("接听", (d, w) -> {
                            webRTCManager.acceptCall(fromUser);
                }).setNegativeButton("拒绝", (d, w) ->
                        webRTCManager.rejectCall(fromUser)).show());
    }
    @Override
    public void onConnectionEstablished() {
        runOnUiThread(() -> Toast.makeText(this, "连接已建立", Toast.LENGTH_SHORT).show());
    }
    @Override
    public void onConnectionClosed() {
        runOnUiThread(() -> {
            Toast.makeText(this, "连接已断开", Toast.LENGTH_SHORT).show();
            localVideoView.clearImage();
            remoteVideoView.clearImage();
        });
    }
    @Override
    public void onError(String error) {
        runOnUiThread(() ->
                Toast.makeText(this, "发生错误：" + error, Toast.LENGTH_LONG).show());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            localVideoView.release();
            remoteVideoView.release();
            webRTCManager.destroy(); // 确保释放所有资源

        }catch (Exception e){
            System.out.println("错误0101");
        }
        if (isFinishing()) {
            webRTCManager.hangup();
        }
    }
}